package src.World;

import java.io.*;
import src.Main;
import src.GameEngine;
import src.Players.Player;
import src.Packets.Frames;

public class Items
{
    private GameEngine ge;
    private Frames frame;
    public int maxItemAmount, maxBankSize;
    public int maxListedItems, maxGroundItems;
    public ItemList[] itemLists;
    public GroundItem[] groundItems;
    public String[] bonusName = {"Stab", "Slash", "Crush", "Magic", "Range", "Stab", "Slash", "Crush", "Magic", "Range", 
		"Strength", "Prayer"
    };
    private int untradable[] = {0};

    public Items()
    {
        ge = Main.m.ge;
        frame = ge.frame;
        maxItemAmount = 999999999;
        maxListedItems = 8000;
        maxGroundItems = 500;
        itemLists = new ItemList[maxListedItems];
        groundItems = new GroundItem[maxGroundItems];
        loadItemList("ITEM.CFG");
        loadItemLists();
        maxBankSize = 352;
    }

    public void process()
    {
        /* Processes every second. */
        for(GroundItem g : groundItems)
        {
            if(g == null)
            {
                continue;
            }
            else if(g.getId() > -1 && g.getAmt() > 0)
            {
                g.updateTime(1);
                if(g.getTime() == 60)
                {
                    if(!isUntradable(g.getId()) && !g.getOwner().equals(""))
                    {
                        frame.removeGroundItem(g.getId(), g.getX(), g.getY(), g.getHeight(), ge.players[ge.getIdFromName(g.getOwner())]);
                        createGlobalItem(g.getId(), g.getAmt(), g.getX(), g.getY(), g.getHeight());
                    }
                }
                else if(g.getTime() <= 0)
                {
                    if(isUntradable(g.getId()))
                    {
                        frame.removeGroundItem(g.getId(), g.getX(), g.getY(), g.getHeight(), ge.players[ge.getIdFromName(g.getOwner())]);
                    }
                    else
                    {
                        removeGlobalItem(g.getId(), g.getX(), g.getY(), g.getHeight());
                    }
                    discardItem(g);
                }
            }
            else if(g.getId() < 0)
            {
                discardItem(g);
            }
            else if(g.getAmt() <= 0)
            {
                discardItem(g);
            }
        }
    }

    public void loadItems(Player p)
    {
        if(p == null)
        {
            return;
        }
        for(GroundItem g : groundItems)
        {
            if(g == null || g.getId() < 0)
            {
                continue;
            }
            if((g.getTime() <= 60 || g.getOwner().equals("")) && !isUntradable(g.getId()) || g.getOwner().equalsIgnoreCase(p.username))
            {
                frame.removeGroundItem(g.getId(), g.getX(), g.getY(), g.getHeight(), p); //Just in case.
                frame.createGroundItem(g.getId(), g.getAmt(), g.getX(), g.getY(), g.getHeight(), p);
            }
        }
    }

    public void createGroundItem(int id, int amt, int x, int y, int height, String owner)
    {
        if(id < 0 || amt < 0)
        {
            return;
        }
        /* Set the owner to "" for an item everyone can see. */
        int index = -1;
        for(int i = 0; i < maxGroundItems; i++)
        {
            if(groundItems[i] == null)
            {
                index = i;
                break;
            }
        }
        if(index == -1)
        {
            Main.m.log("Max number of items spawned");
            return;
        }
        groundItems[index] = new GroundItem(index, id, amt, x, y, height, owner);
        if(groundItems[index].getOwner().equals(""))
        {
            createGlobalItem(id, amt, x, y, height);
        }
        else
        {
            frame.createGroundItem(id, amt, x, y, height, ge.players[ge.getIdFromName(owner)]);
        }
    }

    public int itemExists(int itemId, int itemX, int itemY, int height)
    {
        if(itemId < 0)
        {
            return -1;
        }
        for(GroundItem g : groundItems)
        {
            if(g == null)
            {
                continue;
            }
            if(g.getId() == itemId && g.getX() == itemX && g.getY() == itemY && g.getHeight() == height)
            {
                return g.getIndex();
            }
        }
        return -1;
    }

    public boolean itemPickedup(int itemId, int itemX, int itemY, int height)
    {
        if(itemId < 0)
        {
            return false;
        }
        int amt = 0;
        for(GroundItem g : groundItems)
        {
            if(g == null)
            {
                continue;
            }
            if(g.getId() == itemId && g.getX() == itemX && g.getY() == itemY && g.getHeight() == height)
            {
                amt = g.getAmt();
                if((g.getTime() <= 60 || g.getOwner().equals("")) && !isUntradable(g.getId()))
                {
                    removeGlobalItem(g.getId(), g.getX(), g.getY(), g.getHeight());
                }
                else
                {
                    frame.removeGroundItem(g.getId(), g.getX(), g.getY(), g.getHeight(), ge.players[ge.getIdFromName(g.getOwner())]);
                }
                discardItem(g);
                return true;
            }
        }
        return false;
    }

    public void discardItem(GroundItem g)
    {
        groundItems[g.getIndex()].destruct();
        groundItems[g.getIndex()] = null;
    }

    public void removeGlobalItem(int id, int x, int y, int height)
    {
        if(id < 0)
        {
            return;
        }
        for(Player p : ge.players)
        {
            if(p == null)
            {
                continue;
            }
            frame.removeGroundItem(id, x, y, height, p);
        }
    }

    public void createGlobalItem(int id, int amt, int x, int y, int height)
    {
        if(id < 0 || amt < 0)
        {
            return;
        }
        for(Player p : ge.players)
        {
            if(p == null)
            {
                continue;
            }
            frame.createGroundItem(id, amt, x, y, height, p);
        }
    }

    public boolean isUntradable(int item)
    {
        for(int i = 0; i < untradable.length; i++)
        {
            if(untradable[i] == item)
                return true;
        }
        return false;
    }

    private void loadItemLists()
    {
        int itemId = -1, counter = 0;
        String name = null;
        try
        {
            BufferedReader in = new BufferedReader(new FileReader("./src/Data/DAT/STACKABLE.DAT"));
            while ((name = in.readLine()) != null)
            {
                itemId = Integer.parseInt(name);
                if(itemId != -1)
                {
                    if(itemLists[itemId] != null)
                    {
                        itemLists[itemId].setStackable(true);
                    }
                }
            }
            in.close();
            in = null;
        }
        catch(IOException e)
        {
            Main.m.log("Error loading stackable list.");
        }
        try
        {
            itemId = 0;
            FileInputStream dataIn = new FileInputStream(new File("./src/Data/DAT/NOTES.DAT"));
            while ((itemId = dataIn.read()) != -1)
            {
                if(itemId == 0)
                {
                    if(itemLists[counter] != null)
                    {
                        itemLists[counter].setNote(true);
                    }
                }
                counter++;
            }
            dataIn.close();
            dataIn = null;
        }
        catch(IOException e)
        {
            Main.m.log("Error loading notes list.");
        }
    }

    public boolean stackable(int itemId)
    {
        if(itemLists[itemId] != null)
        {
            return (itemLists[itemId].isStackable());
        }
        return false;
    }

    public boolean noted(int itemId)
    {
        if(itemLists[itemId] != null)
        {
            return (itemLists[itemId].isNote());
        }
        return false;
    }

    public String getItemName(int itemId)
    {
        if(itemId == -1)
        {
            return new String("Unarmed");
        }
        if(itemLists[itemId] != null)
        {
            return (itemLists[itemId].getItemName());
        }
        return new String("Item " + itemId);
    }

    public int getItemValue(int itemId)
    {
        if(itemLists[itemId] != null)
        {
            return (itemLists[itemId].getDropValue());
        }
        return 1;
    }

    private boolean loadItemList(String fileName)
    {
        String line = "", token = "", token2 = "", token2_2 = "", token3[] = new String[10];
        BufferedReader list = null;
        try
        {
            list = new BufferedReader(new FileReader("./src/Data/CFG/" + fileName));
            line = list.readLine().trim();
        }
        catch(Exception e)
        {
            Main.m.log("Error loading item list");
            return false;
        }
        while(line != null)
        {
            int spot = line.indexOf("=");
            if(spot > -1)
            {
                token = line.substring(0, spot).trim();
                token2 = line.substring(spot + 1).trim();
                token2_2 = token2.replaceAll("\t\t", "\t");
                token2_2 = token2_2.replaceAll("\t\t", "\t");
                token2_2 = token2_2.replaceAll("\t\t", "\t");
                token3 = token2_2.split("\t");
                if(token.equals("item"))
                {
                    int[] bonuses = new int[12];
                    for(int i = 0; i < 12; i++)
                    {
                        if(token3[(6 + i)] != null)
                        {
                            bonuses[i] = Integer.parseInt(token3[(6 + i)]);
                        }
                        else
                        {
                            break;
                        }
                    }
                    newItemList(Integer.parseInt(token3[0]), token3[1].replaceAll("_", " "), token3[2].replaceAll("_", " "), Integer.parseInt(token3[4]), Integer.parseInt(token3[4]), Integer.parseInt(token3[6]), bonuses);
                }
            }
            else
            {
                if(line.equals("[ENDOFITEMLIST]"))
                {
                    try
                    {
                        list.close();
                    }
                    catch(IOException ioexception)
                    {}
                    list = null;
                    return true;
                }
            }
            try
            {
                line = list.readLine().trim();
            }
            catch(IOException ioexception1)
            {
                try
                {
                    list.close();
                }
                catch(IOException ioexception)
                {}
                list = null;
                return true;
            }
        }
        return false;
    }

    private void newItemList(int ItemId, String ItemName, String ItemDescription, int ShopValue, int LowAlch, int HighAlch, int Bonuses[])
    {
        if(ItemId > maxListedItems)
        {
            Main.m.log("maxListedItems to low");
            return;
        }
        itemLists[ItemId] = new ItemList(ItemId, ItemName, ItemDescription, ShopValue, LowAlch, Bonuses);
    }

    public int getMaxListedItems()
    {
        return maxListedItems;
    }
}